<template>
  <div class="pageheader">
    <el-page-header @back="$router.back()">
      <template #content>
        <span> {{ info.solution.name }} 方案指标 </span>
      </template>
    </el-page-header>
  </div>
  <el-card class="controlpanel" shadow="never">
    <!--    <el-button @click="saveBasicData" :disabled="step !== 0">校验并保存基本数据</el-button>-->
    <!-- <el-button @click="skipBasicData" :disabled="step !== 0">编辑其他信息</el-button> -->
    <!-- <el-button @click="toFirstStep" :disabled="step === 0">更改基本数据</el-button> -->
    <el-button type="primary" @click="this.indicatorDialogState.visible = true;">编辑指标</el-button>
    <el-button type="primary" @click="submitIndicators">提交数据</el-button>
    <!--    <el-button type="primary" @click="downloadTemplate">下载模板</el-button>-->
    <!--    <el-upload action="#" :auto-upload="false" :multiple="false" :limit="1" :on-change="addFile" :on-remove="removeFile">-->
    <!--      <el-button type="primary">上传模板</el-button>-->
    <!--    </el-upload>-->
    <!-- <el-button type="primary" @click="uploadTemplate">解析模板</el-button> -->
    <!-- <el-button type="primary" @click="test">添加指标</el-button> -->
  </el-card>
  <el-card class="controlpanel" shadow="never">
    指标号：
    <el-input class="w-50 m-2" style="width: 100px;margin-right: 20px" v-model="lineInput.mark"></el-input>
    数据：
    <el-input class="w-50 m-2" style="width: 300px;margin-right: 20px" placeholder="请输入数据"
              v-model="lineInput.value"></el-input>
    分隔符：
    <el-input class="w-50 m-2" style="width: 100px;margin-right: 20px" v-model="lineInput.separator"></el-input>
    <el-button type="primary" @click="changeDataByLine">按行添加</el-button>
  </el-card>
  <el-tabs v-model="activeName" type="border-card" class="tabs">
    <el-tab-pane v-for="(table, index) in tableDict" :key="index" :label="table.tableName" :name="index">
      <el-scrollbar>
        <table border="1" style="width: 100%">
          <th :colspan="50">{{ table.tableName }}表</th>
          <tr v-if="table.isArray !== 0">
            <td :colspan="2">标号及项目名称</td>
            <td :rowspan="2">单位</td>
            <td :rowspan="2">合计</td>
            <td :colspan="basicInfo.consYear">建设期</td>
            <td :colspan="basicInfo.operYear">运营期</td>
          </tr>
          <tr>
            <td style="width: 30px">序号</td>
            <td>项目</td>
            <td v-if="table.isArray !== 1">单位</td>
            <template v-if="table.isArray === 0">
              <td>数据</td>
            </template>
            <template v-else>
              <td v-for="(year, index) in basicInfo.calcYear" :key="index">
                第{{ index + 1 }}年
              </td>
            </template>
          </tr>
          <template v-for="(item, index) in table.indicatorMarks" :key="index">
            <tr
                v-if="indicatorDict[item] !== undefined && indicatorDict[item].indicatorName !== '' && indicatorDict[item].indicatorName !== null">
              <td style="text-align: left">
                {{ table.viewMarks[index] }}
              </td>
              <td>{{ indicatorDict[item].indicatorName }}</td>
              <td>{{ indicatorDict[item].unit }}</td>
              <template v-if="table.isArray === 0">
                <td v-if="indicatorDict[item].formula === 'OPTIONAL'">
                  <el-select v-model="dataSheet[item][0]" class="input-number" :size="inputNumberSize">
                    <el-option v-for="(opt, index) in indicatorDict[item].option" :key="index" :value="index"
                               :label="opt"></el-option>
                  </el-select>
                </td>
                <td v-else>
                  <el-input-number @change="calcYearChange(item);changeLength()"
                                   :disabled="indicatorDict[item].formula !== 'INPUT'"
                                   v-model="dataSheet[item][0]" class="input-number" :size="inputNumberSize"
                                   controls-position="right"
                                   placeholder="请输入"></el-input-number>
                </td>
              </template>
              <template v-else>
                <td>
                  {{ dataSheet[item][dataSheet[item].length - 1] }}
                </td>
                <template v-for="(element, index) in dataSheet[item]" :key="index">
                  <td v-if="index !== dataSheet[item].length - 1">
                    <el-input-number v-model="dataSheet[item][index]"
                                     :disabled="indicatorDict[item].formula !== 'INPUT'"
                                     class="input-number" :size="inputNumberSize" controls-position="right"
                                     placeholder="请输入"
                                     @change="change(item)"></el-input-number>
                  </td>
                </template>
              </template>
              <!-- <td>{{ state.form.liquidFund.turnOverTime[0] }}</td> -->
            </tr>
          </template>

        </table>
      </el-scrollbar>
    </el-tab-pane>
  </el-tabs>
  <el-dialog v-model="indicatorDialogState.visible" :title="indicatorDialogState.title">
    <el-form :model="indicatorDialogState.form" ref="dlg_form">
      <el-form-item label="标号：" prop="name">
        <el-input v-model="indicatorDialogState.form.indicatorMark"></el-input>
      </el-form-item>
      <el-form-item label="指标名称：" prop="description">
        <el-input v-model="indicatorDialogState.form.indicatorName"></el-input>
      </el-form-item>
    </el-form>
    <el-form>
      <el-text>可以添加的指标有：{{ getCandidateIndicators() }}</el-text>
    </el-form>
    <el-form>
      <el-text>将指标名称设为空白为删除指标</el-text>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clean">返回</el-button>
        <el-button type="primary" @click="submitIndicatorAdd">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import {ref, reactive} from "vue";
import {ElMessage} from "element-plus";
import indicatorApi from "@/api/evaluation/indicator";
import dictApi from "@/api/evaluation/dict";
import router from "@/router";
import {ElLoading} from "element-plus";

// 初始化项目基本信息
export default {
  props: {
    projectType: {default: 1, type: Number}
  },
  data() {
    return {
      routeName: router.currentRoute.value.name,
      urlPrefix: "",
      info: {
        project: {
          id: 0,
          name: "",
          projectType: 1,
          description: "",
          createTime: ""
        },
        solution: {}
      },
      activeName: ref(0),
      basicInfo: reactive({
        calcYear: 1,
        consYear: 1,
        operYear: 0,
        transportationFangan: 0,
      }),
      dataSheet: reactive({}),
      tableDict: ref([]),
      indicatorDict: ref({}),
      excelFile: ref(),
      lineInput: reactive({
        mark: "",
        value: "",
        separator: ""
      }),
      indicatorDialogState: reactive({
        visible: false,
        isAdd: true,
        title: "编辑指标",
        form: {
          solutionId: 0,
          indicatorMark: "",
          indicatorName: "",
        }
      }),
      // loadingInstance: ElLoading.service({}),
      basicInfoSaved: ref(false),
      inputNumberSize: "small"
    }
  },
  methods: {
    getIndicatorDict() {
      dictApi.getIndicators(this.info.solution.id, this.projectType).then((res) => {
        if (res.status === 200 && res.data.code === 200) {
          this.indicatorDict = res.data.data;
          this.loadOptions();
        } else {
          ElMessage.error("获取指标字典失败")
        }
      })
    }
    ,
    getTableDict() {
      dictApi.getInTables(this.info.solution.id, this.projectType).then((res) => {
        if (res.status === 200 && res.data.code === 200) {
          this.tableDict = res.data.data;
          // this.createSheet();
        } else {
          ElMessage.error("获取表格字典失败")
        }
        // for (let i of res.data.data) {
        //   if (i.tag === "IN") {
        //     this.tables.push(i);
        //   }
        // }
      })
    }
    ,
    getData() {
      indicatorApi.solutionIndicators(this.info.solution.id).then((res) => {
            if (res.status === 200 && res.data.code === 200) {
              for (let key in res.data.data) {
                this.dataSheet[key] = res.data.data[key];
              }
              if (this.projectType == 1) {
                this.basicInfo.calcYear = this.dataSheet["1.1"][0];
                this.basicInfo.consYear = this.dataSheet["1.2"][0];
                this.basicInfo.operYear = this.dataSheet["1.3"][0];
                // 设置默认值
                this.dataSheet["1.4"] = this.dataSheet["1.4"][0] != 0 ? this.dataSheet["1.4"] : [0.15];
                this.dataSheet["1.8"] = this.dataSheet["1.8"][0] != 0 ? this.dataSheet["1.8"] : [0.046];
                this.dataSheet["4"] = this.dataSheet["4"][0] != 0 ? this.dataSheet["4"] : [0.0672];
              } else if (this.projectType == 2 || this.projectType == 5) {
                this.basicInfo.calcYear = this.dataSheet["X+Y"][0];
                this.basicInfo.consYear = this.dataSheet["X"][0];
                this.basicInfo.operYear = this.dataSheet["Y"][0];
              } else if (this.projectType == 4) {
                this.basicInfo.calcYear = this.dataSheet["X"][0];
              }

            } else {
              ElMessage.error("获取指标数据失败")
            }
          }
      )
    }
    ,
    // 提交
    submitIndicators() {
      indicatorApi.updateIndicators(this.info.solution.id, this.dataSheet).then((res) => {
            if (res.status === 200) {
              if (res.data.code === 200) {
                ElMessage.success("保存成功");
              } else {
                ElMessage.error(res.data.message);
              }
            } else {
              ElMessage.error("操作失败")
            }
          }
      )
    }
    ,
    submitIndicatorAdd() {
      let form = this.indicatorDialogState.form
      indicatorApi.addIndicator(form.solutionId, form.indicatorMark, form.indicatorName).then((res) => {
        if (res.status === 200) {
          if (res.data.code === 200) {
            this.dataSheet[form.indicatorMark] = new Array(this.basicInfo.calcYear + 1).fill(0);
            this.indicatorDict[form.indicatorMark].indicatorName = form.indicatorName
            this.clean()
          } else {
            ElMessage.error(res.data.message)
          }
        } else {
          ElMessage.error("操作失败")
        }
      })
    }
    ,
    loadOptions() {
      for (let key in this.indicatorDict) {
        if (this.indicatorDict[key].memo !== null)
          this.indicatorDict[key].option =
              this.indicatorDict[key].memo.split(" ");
      }
    }
    ,
    // 创建新数据模板
    createSheet() {
      for (let item of this.tableDict) {
        for (let mark of item.indicatorMarks) {
          this.dataSheet[mark] = [0];
        }
      }
    }

    ,
    // 更新计算属性
    change(item) {
      let sum = 0;
      this.toProcess = this.dataSheet[item];
      for (let i = 0; i < this.basicInfo.calcYear; i++) {
        sum += this.toProcess[i];
      }
      this.toProcess[this.basicInfo.calcYear] = sum;
    }
    ,
// 计算期=建设期+运营期
    calcYearChange(item) {
      if (item !== "1.2" && item !== "1.3" && item !== "X" && item !== "Y") {
        return;
      }
      if (this.projectType == 1) {
        if (this.dataSheet["1.1"][0] < 0) {
          this.dataSheet["1.1"][0] = 0;
        }
        if (this.dataSheet["1.2"][0] < 0) {
          this.dataSheet["1.2"][0] = 0;
        }
        if (this.dataSheet["1.3"][0] < 0) {
          this.dataSheet["1.3"][0] = 0;
        }
        this.dataSheet["1.1"][0] = this.dataSheet["1.2"][0] + this.dataSheet["1.3"][0];
        this.basicInfo.calcYear = this.dataSheet["1.1"][0];
        this.basicInfo.consYear = this.dataSheet["1.2"][0];
        this.basicInfo.operYear = this.dataSheet["1.3"][0];
      } else if (this.projectType == 2 || this.projectType == 5) {
        this.dataSheet["X+Y"][0] = this.dataSheet["X"][0] + this.dataSheet["Y"][0];
        this.basicInfo.calcYear = this.dataSheet["X+Y"][0];
        this.basicInfo.consYear = this.dataSheet["X"][0];
        this.basicInfo.operYear = this.dataSheet["Y"][0];
      } else if (this.projectType == 4) {
        this.basicInfo.calcYear = this.dataSheet["X"][0];
      }

    },
    changeLength() {
      for (let key in this.dataSheet) {
        if (Object.prototype.hasOwnProperty.call(this.indicatorDict, key)) {
          if (this.indicatorDict[key].isArray === 1) {
            let curLen = this.dataSheet[key].length;
            let newLen = this.basicInfo.calcYear + 1;
            this.dataSheet[key].length = newLen;
            if (curLen < newLen) {
              this.dataSheet[key].fill(0, curLen, newLen)
            }
          }
        }
      }
    }
    ,
    clean() {
      this.indicatorDialogState.visible = false;
      this.indicatorDialogState.form.solutionId = this.info.solution.id;
      this.indicatorDialogState.form.indicatorMark = ""
      this.indicatorDialogState.form.indicatorName = ""
    }
    ,
    getCandidateIndicators() {
      let arr = []
      let j = 0
      for (let key in this.indicatorDict) {
        if (this.indicatorDict[key].indicatorName == "")
          arr[j++] = key
      }
      return arr
    }
    ,
    changeDataByLine() {
      let arr = this.lineInput.value.split(this.lineInput.separator)
      if (this.dataSheet[this.lineInput.mark] == null) {
        ElMessage.error("不存在该指标")
        return
      }
      let len = this.dataSheet[this.lineInput.mark].length
      if (this.lineInput.separator == "") {
        ElMessage.error("请输入分隔符")
        return
      } else if (arr.length !== len) {
        ElMessage.error("请输入长度为" + len + "的数组，当前长度为" + arr.length)
        return
      } else

        for (let i = 0; i < len; i++) {
          if (isNaN(parseFloat(arr[i]))) {
            ElMessage.error("第" + (i + 1) + "个不是数字，请重新输入!")
            return
          }
        }

      // 修改数据
      for (let i = 0; i < len - 1; i++) {
        this.dataSheet[this.lineInput.mark][i] = arr[i + 1]
      }

      this.dataSheet[this.lineInput.mark][len - 1] = arr[0]
    }
  }
  ,
  mounted() {
    if (this.projectType == 1) {
      this.urlPrefix = "generic"
    } else if (this.projectType == 2) {
      this.urlPrefix = "infrastructure"
    } else if (this.projectType == 3) {
      this.urlPrefix = "purchase"
    } else if (this.projectType == 4) {
      this.urlPrefix = "repair"
    } else if (this.projectType == 5) {
      this.urlPrefix = "update"
    }
    let proj = window.sessionStorage.getItem(this.urlPrefix + "Project");
    let solu = window.sessionStorage.getItem(this.urlPrefix + "Solution");
    if (proj !== null) {
      this.info.project = JSON.parse(proj);
    } else {
      ElMessage.error("未获取到项目信息！");
    }
    if (solu === null) {
      ElMessage.error("未获取到方案信息！");
    } else {
      this.info.solution = JSON.parse(solu);
    }
    this.getTableDict();
    this.getIndicatorDict();
    if (this.routeName === "solution_edit") {

      this.basicInfoSaved.value = true;
    }
    this.getData();
    // this.loadingInstance.close();
  }
}


</script>
<style lang="scss" scoped>
.controlpanel {
  margin: 20px;
}

.calbtn {
  margin: 20px;
  width: 300px;
}

.tabs > .el-tabs__content {
  width: 100%;
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.tabs {
  margin: 20px;
}

.basicInfoForm {
  width: 100%;

  .input {
    width: 300px;
  }

  td {
    .el-form-item {
      margin: 0;
      padding: 0;

      .el-form-item__content {
        margin: 0;
        text-align: center;
      }
    }
  }
}

/*表格样式*/
table {
  width: 100%;
  background: #ffffff;
  margin: 10px auto;
  border-collapse: collapse;
  border: 1px solid #dcdfe6;
  /*border-collapse:collapse合并内外边距
  (去除表格单元格默认的2个像素内外边距*/
}

th,
td {
  height: 25px;
  line-height: 25px;
  padding: 5px;
  text-align: center;
  border: 1px solid #dcdfe6;
  white-space: nowrap;
  border-collapse: collapse;
  -webkit-transition: all 0.5s, padding 0s;
  transition: all 0.5s, padding 0s;
}

th {
  font-weight: normal;
  border-collapse: collapse;
  background-color: #f0f2f5;
}

tr {
  background: #fff;
  -webkit-transition: all 0.5s, padding 0s;
  transition: all 0.5s, padding 0s;
  border-collapse: collapse;
  border: 1px solid #dcdfe6;
}

tr:hover {
  background: #ecf5ff;
}

td:hover {
  background-color: #d9ecff;
}
</style>
